package com.example.news.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.news.entity.Record
import com.example.news.intent.NewsIntent
import com.example.news.repository.NewsRepository
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

//状态
sealed class NewsState{
    //响应成功，返回结果
    data class Success(val list:List<Record>):NewsState()
    //响应失败，返回原因
    data class Error(val msg:String):NewsState()
    //加载中的状态，比如显示进度……
    object Loading:NewsState()

}
class NewsViewModel:ViewModel() {
    val newsRepository by lazy { NewsRepository() }
    //获取一个存放意图的管道，容量不受限制
    val newsChannel= Channel<NewsIntent>(Channel.UNLIMITED)

    //获取一个可变状态流
    private val _newsState= MutableStateFlow<NewsState>(NewsState.Loading)
    //提供get方法
    val newsState:StateFlow<NewsState>
        get() = _newsState

    init {
        handlerIntent()
    }
    fun handlerIntent(){
        viewModelScope.launch {
            newsChannel.consumeAsFlow().collect{
                when(it){
                    is NewsIntent.getNewsList->
                        getNewsList(it.type,it.page)

                    else -> {}
                }
            }
        }
    }

    private fun getNewsList(type: Int, page: Int) {
        viewModelScope.launch {
            //调网络请求
            newsRepository.getNewsList(type, page).collect{
                if(it.code==0){//请求成功
                    _newsState.value=NewsState.Success(it.data.records)
                }else{//失败
                    _newsState.value=NewsState.Error(it.msg)
                }
            }
        }
    }


}